package com.cqhz.quwan.ui.main

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AlertDialog
import android.view.KeyEvent
import android.view.View
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.SystemConfigBean
import com.cqhz.quwan.model.VersionBean
import com.cqhz.quwan.mvp.home.MainContract
import com.cqhz.quwan.mvp.home.MainPresenter
import com.cqhz.quwan.service.HomeService
import com.cqhz.quwan.ui.base.AbsFragment
import com.cqhz.quwan.ui.base.AbsTabActivity
import com.cqhz.quwan.ui.main.fragment.*
import com.cqhz.quwan.util.*
import com.cqhz.quwan.util.service.DownloadService
import kotlinx.android.synthetic.main.activity_main.*
import me.militch.quickcore.core.HasDaggerInject
import me.militch.quickcore.mvp.model.ModelHelper
import javax.inject.Inject


class MainActivity : AbsTabActivity(), PayEventSubscribe, MainEventSubscribe, MainContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var modelHelper: ModelHelper
    @Inject
    lateinit var mainPresenter: MainPresenter
    private val REQUEST_INSTALL_APP = 0x1001
    private val REQUEST_UNKNOWN_APP_SOURCES = 0x1002
    private val REQUEST_EXTERNAL_STORAGE = 0x1003
    private var oldTime: Long = 0
    private var downloadUrl: String = KeyContract.DOWNLOAD_URL
    var onBackListener: (() -> Boolean)? = null
    private var isShowGuess: Boolean = false
    private val PERMISSIONS_STORAGE = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)


    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun layout(): Int {
        return R.layout.activity_main
    }

    override fun contentViewResId(): Int {
        return R.id.fl_content
    }

    override fun tabRadioGroupResId(): Int {
        return R.id.rg_tab
    }

    override fun tabResIds(): IntArray {
        return intArrayOf(
                R.id.rb_information,
                R.id.rb_live,
                R.id.rb_guess,
                R.id.rb_documentary,
                R.id.rb_mall,
                R.id.rb_mine
        )
    }

    override fun fragments(): ArrayList<AbsFragment> {
        return arrayListOf(
                NewsFragment.newInstance(),
                LiveFragment.newInstance(),
                GuessFragment.newInstance(),
                DocumentaryFragment.newInstance(),
                MallFragment.newInstance(),
                MineFragment.newInstance()
        )
    }

    override fun initData() {
        mainPresenter.attachView(this)
        mainPresenter.getSystemConfig()
        mainPresenter.getVersionConfig()// TODO：测试暂时注销，发版需要开启
        PayEventObserver.register(this)
//        Beta.checkUpgrade(false, false)
    }

    override fun setGuessButton(systemConfigBean: SystemConfigBean) {
        // 1:开0:关
        isShowGuess = systemConfigBean.cval.toInt() == 1
        rb_guess.visibility = if (isShowGuess) View.VISIBLE else View.GONE
        rb_documentary.visibility = if (isShowGuess) View.VISIBLE else View.GONE
        rb_mall.visibility = if (isShowGuess) View.GONE else View.VISIBLE
    }

    override fun setVersionInfo(versionBean: VersionBean) {
        if (versionBean.downloadUrl.startsWith("http")) {
            downloadUrl = versionBean.downloadUrl
        }
        // 判断版本是否需要更新，需要则弹窗
        var version: String = this.getVersion()
        if (version != versionBean.version) {
            AlertDialog.Builder(this)
                    .setCancelable(false)
                    .setTitle("温馨提示")
                    .setMessage("天天趣玩已经发布" + versionBean.version + "版本，为了更好的用户体验请及时更新。")
                    .setPositiveButton("马上更新") { _, _ ->
                        var permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        if (permission != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE)
                        } else {
                            downloadApp()
                        }
                    }.create().show()
        }
    }

    /**
     * 下载APP
     */
    private fun downloadApp() {
        val intent = Intent(this, DownloadService::class.java)
        intent.putExtra(DownloadService.DOWNLOAD_URL, downloadUrl)
        startService(intent)
    }

    /**
     * 安装应用的流程
     */
    private fun installProcess() {
        val haveInstallPermission: Boolean
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 先获取是否有安装未知来源应用的权限
            haveInstallPermission = packageManager.canRequestPackageInstalls()
            if (!haveInstallPermission) {// 没有权限
                AlertDialog.Builder(this)
                        .setCancelable(false)
                        .setTitle("温馨提示")
                        .setMessage("安装天天趣玩需要打开未知来源权限，请去设置中开启权限")
                        .setPositiveButton("去设置") { _, _ ->
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                //请求安装未知应用来源的权限
                                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.REQUEST_INSTALL_PACKAGES), REQUEST_INSTALL_APP)
                            }
                        }.create().show()
                return
            }
        } else {
            // 有权限，开始安装应用程序
            DownloadService.installApk(this)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_UNKNOWN_APP_SOURCES -> installProcess()
            else -> {
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_INSTALL_APP -> if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                DownloadService.installApk(this)
            } else {
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                startActivityForResult(intent, REQUEST_UNKNOWN_APP_SOURCES)
            }
            REQUEST_EXTERNAL_STORAGE -> downloadApp()
        }
    }

    override fun checkEvent(checked: Int) {
        Thread {
            runOnUiThread {
                checkIndex(checked)
            }
        }.start()
    }

    override fun doPayFinish() {
        val t = Thread {
            runOnUiThread {
//                checkIndex(2)
            }
        }
        t.start()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val log = CLogger(this::class.java)
        log.e("重新打开")
    }

    private fun setDrawable(state: Int) {
        if (state == KeyContract.STATE_FOCUS_MATCH) {
            rb_information.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.tab_information_pressed, 0, 0)
            rb_live.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.tab_live_pressed, 0, 0)
            rb_guess.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.tab_guess_pressed, 0, 0)
            rb_documentary.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.tab_documentary_pressed, 0, 0)
            rb_mall.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.tab_mall_pressed, 0, 0)
            rb_mine.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.tab_mine_pressed, 0, 0)
        } else {
            rb_information.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.sel_tab_information, 0, 0)
            rb_live.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.sel_tab_live, 0, 0)
            rb_guess.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.sel_tab_guess, 0, 0)
            rb_documentary.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.sel_tab_documentary, 0, 0)
            rb_mall.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.sel_tab_mall, 0, 0)
            rb_mine.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.sel_tab_mine, 0, 0)
        }
    }

    override fun onStart() {
        super.onStart()
        modelHelper.request(modelHelper.getService(HomeService::class.java)
                .switchActivity(AppUtils.getAppVersionName(), DeviceUtils.getAndroidID(), DeviceUtils.getModel(), "Android", "", ""
                        , "", "", "", ""), {
            PreferenceHelper.getInstance(this).putInt(KeyContract.STATE, it.toInt())
            setDrawable(it.toInt())
        }, {
            val int = PreferenceHelper.getInstance(this).getInt(KeyContract.STATE, KeyContract.STATE_HOT_MATCH)
            setDrawable(int)
        })
    }

    override fun onResume() {
        super.onResume()
//        Beta.checkUpgrade(false, false)
        MainEventObserver.register(this)
    }

    override fun onDestroy() {
        mainPresenter.detachView()
        super.onDestroy()
        (application as APP?)?.isStart = false
        PayEventObserver.unregister(this)
        MainEventObserver.remove(this)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            val s = onBackListener?.invoke()
            if (s == null || !s) {
                val current = System.currentTimeMillis()
                if ((current - oldTime) > 3000) {
                    showToast("再按一次退出")
                    oldTime = current
                } else {
                    finish()
                }
            }
        }
        return true
    }
}
